package com.yoke;

import com.yoke.util.CmdUtil;
import com.yoke.util.FileUtil;
import com.yoke.util.HttpUtil;
import com.yoke.util.XmlUtil;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiangzeyin
 * Created by jiangzeyin on 2017/2/16.
 */
public class main {
    private static String path = "D:/Ide/ad_tools/good_tools/";
    //static String path = "D:/Ide/yzb/";
    //static String path = "D:/Ide/ztoutiaoboot/";

    private static String baseUrl = "http://192.168.1.222:6543/nexus/service/local/repositories/thirdparty/content/";
    private static String contextUrl = "http://192.168.1.222:6543/nexus/service/local/artifact/maven/content";
    private static List<File> list = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        scannerFile(path);
        for (File file : list) {
            System.out.println("清理：" + file.getPath());
            deleteDir(file);
        }
        System.out.println("处理结束");
    }

    public static void scannerFile(String path) throws DocumentException, IOException, InterruptedException {
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("没有找到文件");
            return;
        }
        File[] files = file.listFiles();
        if (files == null)
            return;
        for (File item : files) {
            String itemPath = item.getPath();
            String itemName = item.getName();
            if (itemName.startsWith(".") || "src".equals(itemName) || itemName.endsWith(".iml"))
                continue;
            if ("pom.xml".equals(itemName)) {
                parsePom(itemPath);
            } else {
                scannerFile(itemPath);
            }
        }
    }

    public static void parsePom(String pomPath) throws DocumentException, IOException, InterruptedException {

        Document document = XmlUtil.read(pomPath);
        Element element = document.getRootElement();
        Element groupId = element.element("groupId");
        if (groupId == null) {
            Element parent = element.element("parent");
            groupId = parent.element("groupId");
        }
        if (groupId == null)
            System.out.println("groupId错误");
        else
            System.out.println(groupId.getData());
        Element artifactId = element.element("artifactId");
        String artifactIdName = artifactId.getData().toString();
        // System.out.println(artifactId.getData());
        Element version = element.element("version");
        if (version == null) {
            System.out.println("错误:" + artifactIdName);
            return;
        }
        String versionName = version.getData().toString();
        String groupIdName = groupId.getData().toString();
        File file = new File(new File(pomPath).getParentFile(), "target/classes");
        File jarFile = packaging(file, versionName, artifactIdName);
        mavenInstall(jarFile.getPath(), groupIdName, artifactIdName, versionName);
        list.add(file.getParentFile());
        //deleteDir();
        //publishPom(pomPath, jarFile.getPath(), groupIdName, artifactIdName, versionName);
        //publishJar(pomPath, jarFile.getPath(), groupIdName, artifactIdName, versionName);
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children != null)
                // 递归删除目录中的子目录下
                for (int i = 0; i < children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    public static File packaging(File classesPath, String version, String name) throws IOException {
        File inf = new File(classesPath, "META-INF/MANIFEST.MF");
        FileUtil.appendFileContext(inf.getPath(), "Manifest-Version: " + version, false);
        Project prj = new Project();
        Zip zip = new Zip();
        zip.setProject(prj);
        File zipFile = new File(classesPath.getParentFile(), name + ".jar");
        zip.setDestFile(zipFile);
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        fileSet.setDir(classesPath);
        //fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
        //fileSet.setExcludes(...); //排除哪些文件或文件夹
        zip.addFileset(fileSet);
        zip.execute();
        return zipFile;
    }

    public static void mavenInstall(String jarPath, String groupId, String artifactId, String version) throws IOException, InterruptedException {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("cmd /k mvn install:install-file -Dfile=")
                .append(jarPath)
                .append(" -DgroupId=")
                .append(groupId)
                .append(" -DartifactId=")
                .append(artifactId)
                .append(" -Dversion=")
                .append(version)
                .append(" -Dpackaging=jar");
        String info = CmdUtil.exec(stringBuffer.toString());
        System.out.println(info);
    }


    public static void publishJar(String pomPath, String jarPath, String groupId, String artifactId, String version) throws IOException, InterruptedException {
        //http://192.168.1.222:6543/repository/maven-public/

        String deleteUrl = String.format("%s/%s/%s/%s/%s-%s.jar", baseUrl, groupId.replace(".", "/"), artifactId, version, artifactId, version);// "/com/yokead/ztoutiao/admin/dsp-admin/1.0/dsp-admin-1.0.jar";
        System.out.println(deleteUrl);
        String info = HttpUtil.delete(deleteUrl);
        System.out.println(info);
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addTextBody("r", "thirdparty")
                .addTextBody("hasPom", "true")
                .addTextBody("c", "")
                .addTextBody("e", "jar")
                .addBinaryBody("file", new File(pomPath))
                .addBinaryBody("file", new File(jarPath)).build();
        System.out.println(contextUrl);
        info = HttpUtil.post(contextUrl, httpEntity);
        System.out.println(info);
    }
}
